package com.twm.tamauth.engine.exception

import android.view.View
import com.twm.tamauth.engine.MyAuthNetConfig
import com.twm.tamauth.R
import com.twm.tamauth.engine.log.MyAuthLogRecorder
import java.net.UnknownHostException

interface MyAuthNetErrorHandler {

    companion object DEFAULT : MyAuthNetErrorHandler

    /**
     * 全局的网络错误处理
     *
     * @param e 发生的错误
     */
    fun onError(e: Throwable) {
        val message = when (e) {
            is UnknownHostException -> MyAuthNetConfig.app.getString(R.string.net_host_error)
            is MyAuthURLParseException -> MyAuthNetConfig.app.getString(R.string.net_url_error)
            is MyAuthNetConnectException -> MyAuthNetConfig.app.getString(R.string.net_connect_error)
            is MyAuthNetSocketTimeoutException -> MyAuthNetConfig.app.getString(
                R.string.net_connect_timeout_error,
                e.message
            )
            is MyAuthDownloadFileException -> MyAuthNetConfig.app.getString(R.string.net_download_error)
            is MyAuthConvertException -> MyAuthNetConfig.app.getString(R.string.net_parse_error)
            is MyAuthRequestParamsException -> MyAuthNetConfig.app.getString(R.string.net_request_error)
            is MyAuthServerResponseException -> MyAuthNetConfig.app.getString(R.string.net_server_error)
            is NullPointerException -> MyAuthNetConfig.app.getString(R.string.net_null_error)
            is MyAuthNoCacheException -> MyAuthNetConfig.app.getString(R.string.net_no_cache_error)
            is MyAuthResponseException -> e.message
            is MyAuthHttpFailureException -> MyAuthNetConfig.app.getString(R.string.request_failure)
            is MyAuthNetException -> MyAuthNetConfig.app.getString(R.string.net_error)
            else -> MyAuthNetConfig.app.getString(R.string.net_other_error)
        }

        MyAuthLogRecorder.debug(e)
    }

    /**
     * 当你使用包含缺省页功能的作用域中发生错误将回调本函数处理错误
     *
     * @param e 发生的错误
     * @param view 缺省页, StateLayout或者PageRefreshLayout
     */
    fun onStateError(e: Throwable, view: View) {
        when (e) {
            is MyAuthConvertException,
            is MyAuthRequestParamsException,
            is MyAuthResponseException,
            is NullPointerException -> onError(e)
            else -> MyAuthLogRecorder.debug(e)
        }
    }
}